#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author:heqiang
# 与公众号接发消息，校验token
# https://www.cnblogs.com/donghaoblogs/p/10389685.html

import hashlib
from webService.handle import *
import os

app = Flask(__name__, template_folder='../templates')
app.debug = True


@app.route('/')  # 默认网址
def index():
    file = "static/img1.jpg"
    return render_template('index.html', file=file)


@app.route('/static/<name>')
def showimg(name):
    root_dir = os.path.abspath(os.path.dirname(__file__))
    img_data = open("%s/../static/%s" % (root_dir, name), mode="rb").read()
    response = make_response(img_data)
    response.headers["Content-Type"] = "image/jpg"
    return response


@app.route('/wx', methods=['GET', 'POST'])
def wechat_auth():  # 处理微信请求的处理函数，get方法用于认证，post方法取得微信转发的数据
    # 微信公众平台开发时，微信推送消息的机制是推送过来后如果5秒内收不到响应则认为没有推送成功，会再次推送，如果5秒内仍没有收到响应继续推送，总共推送三次。

    if request.method == 'GET':
        token = 'jiuhuacanmandishang'  # 这里填公众号里设置的token。
        data = request.args
        signature = data.get('signature', '')
        timestamp = data.get('timestamp', '')
        # 1）获取请求的四个参数signature、echostr、timestamp、nonce
        # 2）对token（代码里指定）、timestamp参数、nonce参数进行字典排序
        # 3）将三个参数字符串拼接成一个字符串并进行sha1加密
        # 4）对加密后的字符串与请求获取的signature对比，如果一样，返回echostr，对接成功
        nonce = data.get('nonce', '')
        echostr = data.get('echostr', '')
        s = [timestamp, nonce, token]
        s.sort()
        s = ''.join(s)
        s = s.encode(encoding='utf-8')
        # 加密后的token匹配上signature
        hashcode = hashlib.sha1(s).hexdigest()
        if hashcode == signature:
            return make_response(echostr)
        else:
            return 'signature is error'
    else:
        token = 'jiuhuacanmandishang'  # 这里填公众号里设置的token。
        data = request.args
        signature = data.get('signature', '')
        timestamp = data.get('timestamp', '')
        # print(timestamp)
        nonce = data.get('nonce', '')
        echostr = data.get('echostr', '')
        s = [timestamp, nonce, token]
        s.sort()
        s = ''.join(s)
        s = s.encode(encoding='utf-8')
        # 加密后的token匹配上signature
        hashcode = hashlib.sha1(s).hexdigest()
        if hashcode == signature:
            rec = request.stream.read()

            resp = recv_reply_msg(rec)

            return make_response(resp)
        else:
            return 'signature is error'


@app.route('/ordercheck', methods=['GET', 'POST'])
def WxOrderCheck():
    """
    提供给检查订单的进程，调用
    原理：进程通过web接口发送消息，让后台做一次订单检查
    """
    if request.method == 'GET':
        aetaoke.check_order_once()
        response = make_response("ok")
        response.headers['content-type'] = 'application/xml'
        return response
    elif request.method == "POST":
        aetaoke.check_order_once()
        response = make_response("ok")
        response.headers['content-type'] = 'application/xml'
        return response


@app.route('/notify', methods=['GET', 'POST'])
def WXPayView():
    """
    支付回调接口，目前不做检查，直接返回成功
    """
    data = request.args
    response = make_response("success")
    response.headers['content-type'] = 'application/xml'
    return response


@app.route('/pay', methods=['GET', 'POST'])
def WXpay():
    """
    支付接口，通过传参，与微信通信生成订单，最后跳转到支付页面
    """
    data = request.args
    ret_params = aetaoke.pay_order(data["wx"], fee=int(data["fee"]) * 100)
    print(ret_params)
    return render_template('wx_js_pay.html', **ret_params)


@app.route('/img', methods=['GET', 'POST'])
def imgShow():
    """

    """
    return render_template('index.html')


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=80, debug=True)
